package com.uploadfile.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/solid")
public class solidController {

    @PostMapping("/upload")
    public ModelAndView upload(@RequestParam("imgs") MultipartFile[] imgs, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("3d");
        List<String> pathList = new ArrayList<>();
        for (MultipartFile img : imgs) {
            if (img.getSize() > 0) {
                String path = request.getSession().getServletContext().getRealPath("file");
                String fileName = img.getOriginalFilename();
                File file = new File(path, fileName);
                if (!file.exists())
                    file.mkdirs();
                try {
                    img.transferTo(file);
                    pathList.add("/file/" + fileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        modelAndView.addObject("pathList", pathList);
        return modelAndView;

    }
}
